package com.bbtShop.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bbtShop.config.BizException;
import com.bbtShop.core.model.*;
import com.bbtShop.dao.ProductMapper;
import com.bbtShop.dao.SalesHandRecodeMapper;
import com.bbtShop.dao.SalesHandRecodeViewMapper;
import com.bbtShop.dao.SalesHandUserNameViewMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;

/**
 * @author : manke
 * @Description
 * @Date: 2020/10/24 16:06
 */
@Service
public class SalesHandRecodeService {

    @Autowired
    private SalesHandRecodeMapper salesHandRecodeMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private SalesHandRecodeViewMapper salesHandRecodeViewMapper;
    @Autowired
    private SalesHandUserNameViewMapper salesHandUserNameViewMapper;

    public IPage<SalesHandUserNameView> getList(Integer pageNum, Integer pageSize,
                                          SalesHandUserNameView salesHandUserNameView) {
        IPage<SalesHandUserNameView> page = new Page<>(pageNum == null ? 1 : pageNum,
                pageSize == null ? 10 : pageSize);
        LambdaQueryWrapper<SalesHandUserNameView> productLambdaQueryWrapper = new LambdaQueryWrapper<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(salesHandUserNameView.getDate());
        productLambdaQueryWrapper.like(SalesHandUserNameView::getDate,format);
        return salesHandUserNameViewMapper.selectPage(page, productLambdaQueryWrapper);

    }

    public void addUpdate(SalesHandRecode salesHandRecode) {
        if (salesHandRecode.getId() == null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(salesHandRecode.getDate());
            List<SalesHandRecode> salesHandRecodes = salesHandRecodeMapper.selectList(new LambdaQueryWrapper<SalesHandRecode>()
                    .eq(SalesHandRecode::getDate, format).eq(SalesHandRecode::getUserId, salesHandRecode.getUserId()));
            if (salesHandRecodes.size() > 0) {
                throw new BizException(ResultCode.PRODUCT_NOT_ALLOW);
            }
            String salesRecode = salesHandRecode.getSalesRecode();
            Map<String, String> numAndPrice = getNumAndPrice(salesRecode);
            salesHandRecode.setSalesMoney(new BigDecimal(numAndPrice.get("price")));
            salesHandRecode.setSalesNum(Integer.parseInt(numAndPrice.get("num")));
            salesHandRecode.setAddTime(new Date());
            salesHandRecode.setUpdTime(new Date());
            salesHandRecodeMapper.insert(salesHandRecode);

        } else {

            if (salesHandRecode.getSalesRecode() != null && !"".equals(salesHandRecode.getSalesRecode())) {
                String salesRecode = salesHandRecode.getSalesRecode();
                Map<String, String> numAndPrice = getNumAndPrice(salesRecode);
                salesHandRecode.setSalesRecode(salesRecode);
                salesHandRecode.setSalesMoney(new BigDecimal(numAndPrice.get("price")));
                salesHandRecode.setSalesNum(Integer.parseInt(numAndPrice.get("num")));
            }
            salesHandRecode.setUpdTime(new Date());
            salesHandRecodeMapper.updateById(salesHandRecode);
        }

}

    private Map<String, String> getNumAndPrice(String salesRecode) {
        JSONArray objects = JSON.parseArray(salesRecode);
        ObjectMapper objectMapper = new ObjectMapper();
        //查询产品
        List<Product> products = productMapper.selectList(new LambdaQueryWrapper<>());
        int num = 0;
        BigDecimal price = BigDecimal.ZERO;
        for (Object object : objects) {
            HandCountDto handCountDto = objectMapper.convertValue(object, HandCountDto.class);
            if (!handCountDto.getNum().equals("")) {
                int count = Integer.parseInt(handCountDto.getNum());
                num = num + count;
                for (Product product : products) {
                    if (product.getId().toString().equals(handCountDto.getId())) {
                        price = price.add(product.getPrice().multiply(new BigDecimal(count)));
                    }
                }
            }
        }
        HashMap<String, String> res = new HashMap<>();
        res.put("num", String.valueOf(num));
        res.put("price", price.toString());
        return res;
    }

    public void del(Ids ids) {
        salesHandRecodeMapper.deleteBatchIds(ids.getIds());

    }

    public SalesHandRecode getPayInfo(Integer id) {
        return salesHandRecodeMapper.selectById(id);

    }

    public IPage<SalesHandRecodeView>  getListMonth(Integer pageNum, Integer pageSize, SalesHandRecodeView salesHandRecodeView) {
        IPage<SalesHandRecodeView> page = new Page<>(pageNum == null ? 1 : pageNum,
                pageSize == null ? 10 : pageSize);
        LambdaQueryWrapper<SalesHandRecodeView> salesHandRecodeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        String format = simpleDateFormat.format(salesHandRecodeView.getDate());
        salesHandRecodeLambdaQueryWrapper.like(SalesHandRecodeView::getDate,format);
        return salesHandRecodeViewMapper.selectPage(page, salesHandRecodeLambdaQueryWrapper);


    }

    public void delByTime(DatesVo datesVo) {
        for (Date date : datesVo.getDates()) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(date);
            UpdateWrapper<SalesHandRecode> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(SalesHandRecode::getDate,format);
            salesHandRecodeMapper.delete(updateWrapper);
        }
    }
}
